package util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * This Class is used to generate some sorted files for external algorithm comparison
 * @author Songbo Liao
 *
 */
public class data_generator {
	private boolean multi_threads_flag;
	private int files_num;
	private int words_num;
	final String DATA_DIR="data/";
	private static int start =0;
	private static Random random = new Random();
	public data_generator(int filesnum, int wordsnum, boolean flag) {
		this.files_num=filesnum;
		this.words_num=wordsnum;
		this.multi_threads_flag=flag;
		File dir = new File(DATA_DIR);
		if(!dir.exists())
			dir.mkdirs();
	}
	public String get_random_str(int n)
	{
		StringBuffer word = new StringBuffer();
		int tempnum=0;
		char letter;
		for(int i =0 ;i< n;i++)
		{
			tempnum = Math.abs(random.nextInt(52));
			if(tempnum<26)
			{
				letter = (char) (tempnum+'A');
			}
			else
				letter = (char) (tempnum-26 +'a');
			word.append(letter);
		}
		return word.toString();
	}
	
	public void singlerun() throws IOException
	{
		
		BufferedWriter[] bws = new BufferedWriter[this.files_num];
		int num = 0;
		int lnum=0;
		int letternum= 10;
		for(int i=0;i< this.files_num; i++)
		{
			num = random.nextInt(this.words_num/2)+ this.words_num/2;
			bws[i] = new BufferedWriter(new FileWriter(DATA_DIR+i+".data"));
			TreeSet<Integer> sortset = new TreeSet<Integer>();
			for(int j= 0 ;j<num;j++)
			{
				lnum= random.nextInt(letternum/2)+letternum/2;
				sortset.add(Math.abs(random.nextInt(1000000)));
			}
			Iterator<Integer> iterator = sortset.iterator();
			while(iterator.hasNext())
			{
				bws[i].write(String.valueOf(iterator.next()));
				bws[i].newLine();
			}
			bws[i].close();
			sortset = null;
		}
		
 		
	}
	public long multirun() throws InterruptedException
	{
		long time = System.currentTimeMillis();
		ExecutorService exec = Executors.newCachedThreadPool();
		CountDownLatch clock = new CountDownLatch(files_num);
		for(int i=0 ; i<this.files_num;i++)
		{
			exec.execute(new thread_generator(new File(DATA_DIR+i+".data"),this.words_num, i, clock));
		}
		exec.shutdown();
		clock.await();
		return (System.currentTimeMillis()-time);
	}
	public long run() throws IOException, InterruptedException
	{
		long time = System.currentTimeMillis();
		if(this.multi_threads_flag==true)
		{
			multirun();
		}
		else
			singlerun();
		return System.currentTimeMillis()-time;
	}
	public static void main(String[] args) throws IOException, InterruptedException
	{
		
		data_generator generator = new data_generator(4, 10000000, false);
		System.out.println(generator.run());
	}

}
